// 贝盈接收器
import { MousePix } from '../base-sdk/index.js'

// 全局变量存储deviceItem
let globalDeviceItem = null;

export const getBeiyinUuid = async (hidDevice,JsonItem) => {
    console.log('beiyin JsonItem==:',hidDevice,JsonItem)
    try {
        const targetHidDevice = hidDevice
        
        // 如果全局变量已经有deviceItem，直接返回
        if (globalDeviceItem) {
            console.log('贝盈使用缓存的deviceItem:', globalDeviceItem);
            return globalDeviceItem;
        }
        
        // 检查设备是否已经打开，如果没有打开才打开它
        if (!targetHidDevice.opened) {
            try {
                await targetHidDevice.open()
                console.log('贝盈设备已打开:', targetHidDevice.productName)
            } catch (openError) {
                console.error('打开贝盈设备失败:', openError)
                return null
            }
        } else {
            console.log('贝盈设备已经打开:', targetHidDevice.productName)
        }
        
        const ctrl = new MousePix(targetHidDevice,3,'v1')
        const uuidData = await ctrl.getUUID()
        console.log('uuidData:',uuidData)
        const deviceItem = JsonItem?.deviceIds?.find(i => i.id == uuidData.uuid);
        console.log('贝盈匹配到jsonItem:',deviceItem)
        
        // 如果找到deviceItem，保存到全局变量
        if (deviceItem) {
            globalDeviceItem = deviceItem;
        }
        
        return deviceItem
    } catch (error) {
        console.error('获取贝盈UUID时发生错误:', error)
        return null
    }
}